package im_server

import (
	"go.uber.org/zap"
	"pim/pkg/tools"
	"time"
)

func (s *server) StartAutoClearFileTaskService() {

	s.logger.Info("Start StartAutoClearFileTaskService")
	ticker := time.NewTicker(time.Minute * 5)

	for true {
		select {
		case <-s.closeServer:
			s.logger.Debug("Close StartAutoClearFileTaskService")
			timeNow := time.Now()
			doAutoClearFileTaskService(s, timeNow)

			return
		case timeNow := <-ticker.C:
			doAutoClearFileTaskService(s, timeNow)
			s.dao.DoClearKey(timeNow)
		}
	}

}

func doAutoClearFileTaskService(s *server, timeNow time.Time) {
	defer tools.HandlePanic(s.logger, "doAutoClearFileTaskService")
	s.mu.Lock()
	defer s.mu.Unlock()
	currentTime := timeNow.UnixMilli()
	for conn, _ := range s.wsConnToUser {
		for id, info := range conn.cacheUploadFileMap {
			flag := info.CheckStatus(currentTime)
			s.logger.Info("delete file ", zap.String("file", info.Name))
			if flag {
				delete(conn.cacheUploadFileMap, id)
			}
		}
	}

}
